package com.pig4cloud.pig.village.sequence.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pig.village.api.entity.GlobalSequence;
import com.pig4cloud.pig.village.sequence.mapper.SequenceMapper;
import com.pig4cloud.pig.village.sequence.service.ISequenceService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author limbray.li
 * @date 2021/7/19
 */
@Service
@RequiredArgsConstructor
public class SequenceServiceImpl extends ServiceImpl<SequenceMapper, GlobalSequence> implements ISequenceService {

	@Override
	public int nextNum() {
		return nextNum(1);
	}

	@Override
	public int nextNum(int count) {
		String name = DatePattern.PURE_DATE_FORMAT.format(new Date());
		return nextNum(name, count);
	}

	@Override
	@Transactional
	public synchronized int nextNum(String name, int count) {
		//先获取当前值
		LambdaQueryWrapper<GlobalSequence> query = Wrappers.lambdaQuery();
		query.eq(GlobalSequence::getName, name);
		GlobalSequence sequence = super.getOne(query);
		//若为空，设置count，返回1
		if (sequence == null || sequence.getValue() == null) {
			sequence = GlobalSequence.builder().name(name).incre(1).value(count).build();
			super.save(sequence);
			return 1;
		} else {
			//若不为空，+1返回，count*步长 更新
			int result = sequence.getValue() + (count * sequence.getIncre());
			LambdaUpdateWrapper<GlobalSequence> update = Wrappers.lambdaUpdate();
			update.eq(GlobalSequence::getId, sequence.getId());
			update.set(GlobalSequence::getValue, result);
			super.update(update);
			return result;
		}
	}
}
